package model

import (
	"fmt"
	"gorm.io/gorm"
	"shop-api/databases/mysql"
)

type GoodSKU struct {
	Base
	GoodID   uint   `json:"good_id" gorm:"index;not null;comment:商品ID"`                   // 关联商品
	Stock    uint   `json:"stock" gorm:"not null;default:0;comment:库存数量"`                 // 库存
	Price    string `json:"price" gorm:"type:decimal(10,2);not null;comment:SKU价格"`       // 价格
	VipPrice string `json:"vip_price" gorm:"type:decimal(10,2);not null;comment:会员SKU价格"` // 价格
	Image    string `json:"image" gorm:"type:varchar(255);comment:SKU图片"`                 // SKU 具体图片
}

func (m *GoodSKU) GetGoodMinPriceByGoodIDs(goodIDs []uint) ([]*GoodSKU, error) {
	var infos []*GoodSKU
	err := mysql.WithClient(func(db *gorm.DB) error {
		return db.Table("good_skus").
			Select("good_id, MIN(price) as price,MIN(vip_price) as vip_price").
			Where("good_id IN (?)", goodIDs).
			Group("good_id").
			Find(&infos).Error
	})
	fmt.Println(infos)
	if err != nil {
		return nil, err
	}
	return infos, nil
}

func (m *GoodSKU) GetBySkuIDs(skuIDs []uint) ([]*GoodSKU, error) {
	var infos []*GoodSKU
	err := mysql.WithClient(func(db *gorm.DB) error {
		return db.Where("id in (?)", skuIDs).Find(&infos).Error
	})
	if err != nil {
		return nil, err
	}
	return infos, nil
}

type UpdateStock struct {
	SkuID uint `json:"sku_id"`
	Num   uint `json:"num"`
}

func (m *GoodSKU) UpdateStockWithTx(tx *gorm.DB, in []*UpdateStock) error {
	var skuIDs []uint
	for _, val := range in {
		skuIDs = append(skuIDs, val.SkuID)
	}

	var skuInfos []*GoodSKU
	err := tx.Set("gorm:query_option", "FOR UPDATE").Where("id in (?)", skuIDs).Find(&skuInfos).Error
	if err != nil {
		return err
	}

	skuMap := make(map[uint]*GoodSKU)
	for _, val := range skuInfos {
		skuMap[val.ID] = val
	}

	for _, val := range in {
		skuInfo := skuMap[val.SkuID]
		if skuInfo.Stock < val.Num {
			return fmt.Errorf("库存不足")
		}
		err = tx.Model(m).Where("sku_id = ?", val.SkuID).Update("stock", gorm.Expr("stock-", val.Num)).Error
		if err != nil {
			return err
		}
	}
	return nil
}
